<template>
    <div class="main coupon-edit">
        <section>
            <el-form  size="medium" ref="form" label-width="150px" :rules="commonRules" :model="zhongcao" :disabled="isDisabled">
                <div class="block-header"><div>素材内容</div></div>
                <div class="block-content">
                    <el-form-item label="种草标题:" prop="manageTitle" :rules="commonRules.notNullRule">
                        <el-input v-model="zhongcao.manageTitle" placeholder="用于后台快速查找素材，不超过15字" maxlength="15"></el-input>
                    </el-form-item>
                    <el-form-item label="素材类型:" prop="type" :rules="commonRules.notNullRule">
                        <el-radio-group v-model="zhongcao.type" >
                            <el-radio  :label="2">单图文素材</el-radio>
                            <el-radio  :label="4">多图文素材</el-radio>
                            <el-radio  :label="8">视频素材</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="素材标签:" prop="type" :rules="commonRules.notNullRule">
                      <el-checkbox-group v-model="zhongcao.tags">
                        <el-checkbox :label="item.value" :key="item.value" v-for="item in tagList">{{item.text}}</el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="种草文案:" prop="content" :rules="commonRules.notNullRule">
                        <el-input  type="textarea" v-model="zhongcao.content" maxlength="200" placeholder="请输入文案，200字以内，支持特殊符号及表情输入"></el-input>
                    </el-form-item>
                    <el-form-item label="素材图片:" prop="resource" :rules="commonRules.notNullRule"  v-if="zhongcao.type===2">
                        <el-upload
                                class="avatar-uploader"
                                accept="image/*"
                                :action="upladUrl"
                                name="file"
                                :show-file-list="false"
                                :before-upload="beforeUpload"
                                :on-success="(res)=>{
                            zhongcao.resource = replaceImgUrl(res.filePath)
                        }">
                        <img v-if="zhongcao.resource" :src="zhongcao.resource" class="avatar">
                        <i v-if="!zhongcao.resource" class="el-icon-plus avatar-uploader-icon"></i>
                        <span v-if="!zhongcao.resource" class="uploadLocal">本地上传</span>
                        </el-upload>
                        <div style="color: red">单张图片控制在5M以内</div>   
                    </el-form-item>
                    <el-form-item label="素材图片:" prop="resourceList" :rules="commonRules.notNullRule" v-if="zhongcao.type===4">
                        <ul class="upload-img-list">
                            <draggable v-model="zhongcao.resourceList" :options="{group:'resourceList'}" @start="drag=true" @end="drag=false">
                                <li class="img-preview" v-for="(imgItem, imgIndex) of zhongcao.resourceList" :key="imgIndex" >
                                    <img :src="imgItem.resourceUrl" alt="">
                                    <div class="img-preview-mask">
                                        <div class="mask-btn">
                                            <i title="删除" class="el-icon-delete" @click="()=>{ deleteImg(imgIndex)}"></i>
                                        </div>
                                    </div>
                                </li>
                            </draggable>
                            <li>
                                <label class="upload-btn">
                                    <input type="file" @change="(event)=>{uploadImg(event, zhongcao.resourceList)}"/>
                                    <i class="el-icon-plus avatar-uploader-icon"></i>
                                    <span class="uploadLocal">本地上传</span>
                                </label>
                            </li>
                        </ul>
                        <div style="color: red">最多添加9张，单张图片控制在5M以内</div>
                    </el-form-item>
                    <el-form-item label="素材视频:" prop="videoResource" :rules="commonRules.notNullRule"  v-if="zhongcao.type===8">
                        <el-upload 
                                class="avatar-uploader"
                                accept="video/mp4"
                                :action="upladUrl"
                                name="file"
                                ref="upload"
                                :auto-upload="false"
                                :show-file-list="false"
                                :file-list="fileList"
                                :on-change ="beforeUploadVideo"
                                :on-success="(res)=>{zhongcao.videoResource = replaceImgUrl(res.filePath)}">
                            <video v-if="zhongcao.videoResource" autoplay="autoplay" loop="loop"  :src="zhongcao.videoResource" controls>
                                您的浏览器不支持HTML5 Video
                            </video>
                            
                            <i v-if="!zhongcao.videoResource" class="el-icon-plus avatar-uploader-icon"></i>
                            <span v-if="!zhongcao.videoResource" class="uploadLocal">本地上传</span>
                        </el-upload>
                        <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
                        <div style="color: red">视频请控制在5-15秒以内</div>  
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" plain  @click="chooseMaterial">
                            从素材库选择
                        </el-button>
                    </el-form-item>
                    <el-form-item label="视频预览图片:" prop="videoPicUrl" :rules="commonRules.notNullRule" v-if="zhongcao.type===8">
                         <el-upload
                                class="avatar-uploader"
                                accept="image/*"
                                :action="upladUrl"
                                name="file"
                                :show-file-list="false"
                                :limit="1"
                                :before-upload="beforeUpload"
                                :on-success="(res)=>{
                            zhongcao.videoPicUrl = replaceImgUrl(res.filePath)
                        }">
                        <img v-if="zhongcao.videoPicUrl" :src="zhongcao.videoPicUrl" class="avatar">
                        <i v-if="!zhongcao.videoPicUrl" class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <div style="color: red">单张图片控制在5M以内</div>
                    </el-form-item>     
                    <el-form-item label="分享人数:"  prop="initShareNum" :rules="commonRules.numberRule" >
                        <el-input  v-model="zhongcao.initShareNum" placeholder="请输入分享人数"></el-input>
                    </el-form-item> 
                    <!-- <el-form-item label="素材排序:"  prop="sort" :rules="commonRules.numberRule" >
                        <el-input  v-model="zhongcao.sort" placeholder="数字越大越靠前">
                             <template slot="append">已排序至{{sortLast}}</template>
                        </el-input>
                    </el-form-item> -->
                    <el-form-item label="" >
                        <el-button  type="primary" icon="el-icon-circle-plus"  size="medium" @click="chooseGoods">商品</el-button>
                        <el-button type="success"  size="medium" icon="el-icon-circle-plus" @click="choosePackage">套餐</el-button>
                    </el-form-item>
                    <el-form-item label="选择的商品/套餐"  >
                        <el-table :data="zhongcao.goods">
                            <el-table-column align="center" label="名称"  prop="goodsName"></el-table-column>
                            <el-table-column align="center" label="名称">
                                <template slot-scope="scope">
                                    <span>{{scope.row.goodsType === 1? '商品' : '套餐'}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="操作" width="120" fixed="right">
                            <template slot-scope="scope">
                                <a href="javascript: void(0);" class="el-icon-remove" @click="delItem(scope.row, scope.$index)"></a>
                            </template>
                        </el-table-column>    
                        </el-table>    
                    </el-form-item>
                </div>
                <el-form-item label="" style="margin-top:20px;"  v-if="!isDisabled">
                    <el-button type="primary" plain size="medium" :loading="btnLoading" @click="save" >保存</el-button>
                    <el-button type="info" size="medium" plain @click="$router.push({ name: 'zhongcao' })">返回</el-button>
                </el-form-item> 
            </el-form> 
            <el-button type="info" size="medium" plain @click="$router.push({ name: 'zhongcao' })" v-if="isDisabled" style="margin-left:150px">返回</el-button>
        </section>
    </div>
</template>
<script>
import { getTagList } from '../../../api/common'
import draggable from 'vuedraggable'
import differenceBy from 'lodash/differenceBy'
  export default {
    name: 'zhongcaoEdit',
    components: {
      draggable
    },
    mounted(){
        this.zhongcao.id = this.$route.query.id
        if(this.$route.query.issueSource===1) {
            this.isDisabled = true
        } else {
            this.isDisabled = false
        }
        if(this.zhongcao.id) {  
            this.getConfig()
        }
    },
    created(){
      this.getTagList()
        this.getSortLast()
    },
    data(){
        return {
          tagList: [],
            zhongcao: {
                content: '',
                id: '',
                resource: '',
                resourceList: [],
                videoResource:'',
                videoPicUrl:'',
                initShareNum:'',
                sort: '',
                manageTitle: '',
                type: 2,
                tags:[],
                goods:[],
                issueSource:2
            },
            btnLoading: false,
            sortLast:'',
            isDisabled:false,
            playTime:'',
            fileList: []
        }
    },
    methods: {
      // 获取种草标签下拉列表
      getTagList () {
        this.request({
          url: '/zhongcao-web-manage/zhong-cao-manage/article-tags/get',
          method: 'get'
        }).then((res) => {
          this.tagList = res.data
        }).catch(err => {
          console.log(err)
          this.tagList = []
        })
      },
        deleteImg(imgIndex) {
            if(this.isDisabled) {
                return false
            }
            this.zhongcao.resourceList.splice(imgIndex, 1)
        },
        getConfig(){
            this.request({
                url: '/zhongcao-web-manage/zhong-cao-manage/article-detail?id='+this.zhongcao.id,
                method: 'get',
            }).then((res) => {
                let  zhongcaoData = res.data[0]
                this.zhongcao = {
                    ...zhongcaoData,
                    resource: zhongcaoData.type === 2 ? zhongcaoData.resourceObjectList[0].resourceUrl : '',
                    resourceList:zhongcaoData.type === 4 ? zhongcaoData.resourceObjectList  : [],
                    videoResource: zhongcaoData.type === 8 ? zhongcaoData.resourceObjectList[0].resourceUrl : '',
                    videoPicUrl: zhongcaoData.type === 8 ? zhongcaoData.resourceObjectList[0].videoPreviewImg : '',
                    tags: zhongcaoData.tags ? zhongcaoData.tags : []
                }
            }).catch(err => {
               this.$message.error(err.message)
            })
        },
        chooseMaterial() {
            if(this.zhongcao.type===2){
                this.materialLibrary([], 1, 4).then(val => {
                    this.zhongcao.resource = val[0].resource 
                    if(val[0].content){
                        this.zhongcao.content = val[0].content
                    }
                    console.log(this.zhongcao.content)
                }).catch(err => {
                    // this.busMaterial.resource = ''
                })
            }else if(this.zhongcao.type===4){
                this.materialLibrary([], -1, 4).then(val => {
                    if(this.zhongcao.resourceList.length+val.length > 9){
                        this.$message.error('上传超过9张图片')
                        return false
                    }
                    for(var i=0;i<val.length;i++){
                        this.zhongcao.resourceList.push({resourceUrl:val[i].resource})
                        if(val[i].content){
                            this.zhongcao.content += val[i].content
                        }
                    }
                    console.log(this.zhongcao.content)
                }).catch(err => {
                    this.$message.error(err)
                })
            } else if(this.zhongcao.type===8) {
                this.materialLibrary([], 1, 3).then(val => {
                    this.zhongcao.videoResource = val[0].resource
                }).catch(err => {
                    this.zhongcao.videoResource = ''
                })
            }
        },
        chooseGoods() {
            let goodsChecked = []
            this.zhongcao.goods.forEach(item=>{
                if(item.goodsType === 1) {
                    goodsChecked.push({goodsId:item.goodsId, name:item.goodsName})
                }
            })
            this.goodsChoose({count:-1}, goodsChecked).then(val=>{
                let goodsList = this.zhongcao.goods
                let needDelGoods = differenceBy(goodsList, val, 'goodsId')
                let needAddGoods = differenceBy(val, goodsList, 'goodsId')
                let needDelreal = []
                for(var k = 0;k<needDelGoods.length;k++) {
                    if(needDelGoods[k].goodsType === 1) {
                        needDelreal.push(needDelGoods[k])
                    }
                }
                for(var i=0;i<this.zhongcao.goods.length;i++) {
                    for(var j=0;j<needDelreal.length;j++) {
                        if(this.zhongcao.goods[i].goodsId === needDelreal[j].goodsId) {
                            this.zhongcao.goods.splice(i, 1)
                        }
                    }
                }
                needAddGoods.forEach((item)=>{
                    this.zhongcao.goods.push({
                        goodsId: item.goodsId,
                        goodsImageUrl: item.image,
                        goodsName: item.name,
                        goodsType: 1,
                        packType: '',
                        price: item.price
                    })
                }) 
            })
        },
        choosePackage() {
            let packageChecked = []
            this.zhongcao.goods.forEach(item=>{
                if(item.goodsType === 2) {
                    packageChecked.push({packageId:item.goodsId, name:item.goodsName})
                }
            })
            this.packageChoose({count:-1}, packageChecked).then(val=>{
                val.forEach(item=>{
                    item.goodsId = item.packageId 
                })
                let needDelGoods = differenceBy(this.zhongcao.goods, val, 'goodsId')
                let needAddGoods = differenceBy(val, this.zhongcao.goods, 'goodsId')
                let needDelreal = []
                for(var k = 0;k<needDelGoods.length;k++) {
                    if(needDelGoods[k].goodsType === 2) {
                        needDelreal.push(needDelGoods[k])
                    }
                }
                for(var i=0;i<this.zhongcao.goods.length;i++) {
                    for(var j=0;j<needDelreal.length;j++) {
                        if(this.zhongcao.goods[i].goodsId === needDelreal[j].goodsId) {
                            this.zhongcao.goods.splice(i, 1)
                        }
                    }
                }
                needAddGoods.forEach((item)=>{
                    this.zhongcao.goods.push({
                        goodsId: item.goodsId,
                        goodsImageUrl: item.image,
                        goodsName: item.name,
                        goodsType: 2,
                        packType: '',
                        price: item.price
                    })
                })
            })
        },
        save() {
            this.$refs.form.validate(valid => {
                if(valid) {
                    if(this.zhongcao.content.length>200) {
                        this.$message.error('种草文案超过200，请删除一些！')
                        return false
                    }
                    if(this.zhongcao.goods.length>5) {
                        this.$message.error('所选商品和套餐数量超过5条,请移除一些再继续!')
                        return false
                    }
                    var busData ={
                        manageTitle: this.zhongcao.manageTitle,
                        content: this.zhongcao.content,
                        id: this.zhongcao.id,
                        initShareNum:this.zhongcao.initShareNum,
                        sort: this.zhongcao.sort,
                        type: this.zhongcao.type,
                        zhongCaoUserId: this.zhongcao.zhongCaoUserId,
                        goods:this.zhongcao.goods,
                        tags:this.zhongcao.tags,
                        resourceObjectList: [],
                        issueSource: 2
                    }
                    if(this.zhongcao.type === 2) {
                        busData.resourceObjectList.push({resourceUrl:this.zhongcao.resource})
                    } else if(this.zhongcao.type === 4) {
                        this.zhongcao.resourceList.forEach(item=>{
                            busData.resourceObjectList.push(item)
                        })    
                    } else if(this.zhongcao.type === 8) {
                        busData.resourceObjectList.push({
                            resourceUrl:this.zhongcao.videoResource,
                            videoPreviewImg:this.zhongcao.videoPicUrl
                        })
                    }
                    console.log(busData)
                    this.btnLoading = true
                    let zhongcaourl = this.zhongcao.id?'/zhongcao-web-manage/zhong-cao-manage/save-article':'/zhongcao-web-manage/zhong-cao-manage/add-article'
                    this.request({
                        url: zhongcaourl,
                        method: 'post',
                        data: busData
                    }).then(res => {
                        console.log(res)
                        if(res.status===200) {
                            this.$message.success('添加成功')
                            this.btnLoading=false
                            this.$router.push({ name: 'zhongcao' })
                        }
                    }).catch((err)=> {
                        this.btnLoading = false
                    })   
                }     
            })
        },
        uploadImg(event, item) {
            if(item.length > 8) {
                this.$message.error('上传超过9张图片')
                return false
            }
            const file = event.target.files[0]
            if(!file.type.match('image/')){
                 this.$message.error('请上传图片')
                return false
            }
            this.picFileUpload(file, (res) => {
                item.push({resourceUrl: this.replaceImgUrl(res.filePath)});
            }, {limitSize:5})
        },
        beforeUpload(file) {
            if(!file.type.match('image/')){
                 this.$message.error('请上传图片')
                return false
            }
            const isLt5M = file.size / 1024 / 1024 < 5
            if (!isLt5M) {
                this.$message.error('上传图片大小不能超过 5MB!')
            }
            return isLt5M
        },
        beforeUploadVideo(file, fileList) {
            this.fileList = fileList
            if(this.fileList.length>1) {
                this.fileList.splice(0, 1)
            }
             if(!file.raw.type.match('video/mp4')){
                this.$message.error('请上传MP4格式视频')
                return false
            }
            let url = URL.createObjectURL(file.raw)
            var audioElement = new Audio(url)
            setTimeout(()=>{
                this.playTime = audioElement.duration
                if(this.playTime < 5 || this.playTime >= 16) {
                   this.$message.error('请上传5-15秒的视频文件哦')
                    return false
                }else {
                    this.$refs.upload.submit();
                }
            }, 500)
            
        },
        async getSortLast() {
            const sort = await this.request({
                url: '/zhongcao-web-manage/zhong-cao-manage/current-sort',
                method: 'post'
            }).catch((err)=> {
                this.$message.error(err.msg)
            }) 
            if(sort.status===200){
               this.sortLast = sort.data
            }
        },
        delItem(row, index){
            if(this.$route.query.issueSource===1) {
                return false
            }
            this.$confirm(`确定要删除吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                this.zhongcao.goods.splice(index, 1)
            }).catch(err => {
                console.log(err)
            })
        }
    }   
  }
</script>
<style lang="scss">
    @import "../../../styles/_mixin.scss";
    .block-header{
        color: #1ea0ff;
        font-size: 14px;
        padding: 12px 0;
        margin-bottom: 12px;
        background: #f7f7f7;
        &>div{
            padding: 0 12px;
            border-left: 2px solid #1ea0ff;
        }
    }
    .uploadLocal{
        position: absolute;
        bottom: -40px;
        font-size: 16px;
        color: #409EFF;
        left: 60px;
    }
    .coupon-edit .el-form .el-textarea .el-textarea__inner{
        height: auto;
    }
    .adviceTxt{
        color: #8c939d
    }
    .use-type-block{
        @include flex;
        margin-left: 24px;
    }
    .add-btn-block{
        margin:  0 0 12px 24px;
    }
     .section-content{
         .el-input-group__prepend{
             padding: 0 5px;
         }
        .line{
            text-align: center;
        }
        .el-input{
            width: 100%;
            max-width: 500px;
            min-width: 150px;
        }
        .el-icon-delete{
            color: red;
            font-size: 16px;
            margin: 0 12px;
            cursor: pointer;
        }
        .goods-item{
            padding: 12px 0;
            // border: 1px solid #efefef;
            border-radius: 6px;
            position: relative;

            .avatar-uploader .el-upload,
            .upload-img-list li,
            .upload-img-list .upload-btn{
                width: 120px;
                height: 120px;
                line-height: 118px;
            }
            .upload-img-list .img-preview .img-preview-mask .mask-btn {
                margin-top: 47px;
                line-height: 36px;
                text-align: center;
            }

            .present-item{
                padding: 6px;
                border: 1px solid #efefef;
                margin-bottom: 12px;
                position: relative;

                .el-icon-error{
                    color: red;
                    font-size: 18px;
                    cursor: pointer;
                    top: 12px;
                    right: 12px;
                    position: absolute;
                    z-index: 9;
                }

                &>.el-form-item {
                    margin-bottom: 22px;
                }
                .el-input,
                .el-select{
                    width: 100%;
                    max-width: 160px;
                }
            }
        }
        .add-btn-block{
            margin:  0 0 12px 24px;
        }
        .footer-block{
            text-align: center;
            margin-top: 24px;
        }
    }
</style>
